package com.android.thought.badboys;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.ArrayList;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.CallLog;
import android.provider.Telephony.Mms;
import android.provider.Telephony.Sms;
import android.util.Log;

import com.android.thought.badboys.Action.ISmsAction;
import com.android.thought.badboys.Info.CallInfo;
import com.android.thought.badboys.Info.DataConversion;
import com.android.thought.badboys.Info.MessageInfo;
import com.android.thought.badboys.Info.MessageInfo.MESSAGE_TYPE;

public class MessageDeleteTask extends AsyncTask<ISmsAction, Void, Boolean> {
	ISmsAction mListener;

	ProgressDialog mProgressDialog;
	Context mContext;
	int mType = -1;
	ArrayList<DataConversion> mCOnversionData = null;

	

	public MessageDeleteTask(Context context, int Type, ArrayList<DataConversion> infos) {
		mContext = context;
		mType = Type;

		mCOnversionData = infos;
	}

	@Override
	protected Boolean doInBackground(ISmsAction... params) {

		if (mCOnversionData != null && mCOnversionData.size() > 0 && params != null && params.length > 0) {
			mListener = params[0];
			return onLoadData();
		}

		return false;
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		this.mProgressDialog = new ProgressDialog(mContext);
		this.mProgressDialog.setMessage("잠시만 기다려 주세요. \n로딩중입니다.");
		this.mProgressDialog.setCancelable(true);
		this.mProgressDialog.show();

		this.mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {

			@Override
			public void onCancel(DialogInterface dialog) {
				onCancelled();
			}
		});

	}

	@Override
	protected void onCancelled() {
		super.onCancelled();
		if (mListener != null)
			mListener.onLoadComplated(null);
	}

	@Override
	protected void onPostExecute(Boolean returnValue) {
		super.onPostExecute(returnValue);

		if (this.mProgressDialog != null)
			this.mProgressDialog.dismiss();

		this.mProgressDialog = null;
		this.mContext = null;

		if (this.mListener != null)
			this.mListener.onLoadComplated(returnValue);
	}

	private byte[] GetMmsAttachment(String _id, String _data, String fileName)

	{

		Uri partURI = Uri.parse("content://mms/part/" + _id);

		ByteArrayOutputStream baos = new ByteArrayOutputStream();

		InputStream is = null;

		try {

			is = mContext.getContentResolver().openInputStream(partURI);

			byte[] buffer = new byte[256];

			int len = is.read(buffer);

			while (len >= 0) {

				baos.write(buffer, 0, len);

				len = is.read(buffer);
				
				

			}
			
			return baos.toByteArray();

		}

		catch (IOException e)

		{

			e.printStackTrace();

			// throw new MmsException(e);

		}

		finally

		{

			if (is != null)

			{

				try

				{

					ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());

					// writeToFile(bais,"data/",fileName);

					is.close();

					bais.close();

				}

				catch (IOException e)

				{

					e.printStackTrace();

				} // Ignore

			}
		}
		
		return  null;

	}

	public void dd(int id) {
		String smsUri = "content://sms/conversations/";
		Cursor c1 = mContext.getContentResolver().query(Uri.parse(smsUri), null, null, null, null);
		while(c1.moveToNext()) {
			String[] columnNames = c1.getColumnNames();
			for(int i = 0; i < columnNames.length; i++) {
				
				Log.v("CH_DEBUG", columnNames[i] + ":" + c1.getString(i));
				
			}
		}
		c1.close();
		
		
		/*
		Uri uri = Uri.parse("content://com.sec.badge/apps");

		Cursor c = mContext.getContentResolver().query(uri, null, null, null, null);

		// This indicates the provider doesn't exist and you probably aren't running
		// on a Samsung phone running TWLauncher. This has to be outside of try/finally block
		if (c == null) {
		    return;
		}

		try {
		    if (!c.moveToFirst()) {
		        // No results. Nothing to query
		        return;
		    }

		    c.moveToPosition(-1);
		    while (c.moveToNext()) {
		        String pkg = c.getString(1);
		        String clazz = c.getString(2);
		        int badgeCount = c.getInt(3);
		        Log.d("CH_DEBUG", "package: " + pkg + ", class: " + clazz + ", count: " + String.valueOf(badgeCount));
		    }
		} finally {
		    c.close();
		}
		
		*/
	
		ArrayList<String> smapleData = new ArrayList<String>();
		
		
		//smapleData.add(Mms.REPORT_REQUEST_URI.toString());
		//smapleData.add(Mms.REPORT_STATUS_URI.toString());
		
//		smapleData.add("content://mms/part/");
//		smapleData.add("content://mms/outbox/");
//		smapleData.add("content://mms/rate/");
//		smapleData.add("content://mms/drm/");
//		smapleData.add("content://mms/threads/");
////		
		 
		 
		for (String string : smapleData) {
			
			Uri allMessage = Uri.parse(string);
			Cursor 	cursor = mContext.getContentResolver().query(allMessage, null, null, null, null);
			
			Log.d("CH_DEBUG", "####### " + string + " COUNT : "  + 
					( cursor == null ? "COUNT NULL"  : Integer.toString(cursor.getCount())));
			
			if( cursor != null && cursor.getCount() > 0 )  {
				cursor.moveToFirst();
				
				while (!cursor.isAfterLast()  ) {  
				
					String[] coloumns = cursor.getColumnNames();
					String[] values = null;
	
					if (values == null)
						values = new String[coloumns.length];
		
					for (int i = 0; i < cursor.getColumnCount()-1 ; i++) {
						values[i] = cursor.getString(i);
					}
					Log.i( "CH_DEBUG", "#########################"+ string +  "   #############################");
					for (int indexxss = 0; indexxss < values.length; indexxss++) {
						Log.e("CH_DEBUG", "### SAMPLE  : " + coloumns[indexxss] + "::" + values[indexxss]);
					}
					Log.i( "CH_DEBUG", "######################################################");
					
					cursor.moveToNext();
				}
			}
		
			
			if ( cursor != null )
				cursor.close();
			
			cursor = null;
			

            Intent intent = new Intent(Mms.Intents.CONTENT_CHANGED_ACTION);
            intent.putExtra(Mms.Intents.DELETED_CONTENTS, allMessage);
            
     
            mContext.sendBroadcast(intent);
            
			
		}
		
	}
	
	private boolean onLoadData() {
		boolean isReturn = false;
		for (DataConversion conversion : mCOnversionData) {

			// 관리 할 번호 지정
			final String data = conversion.getPhoneInfo().getPhoneNumber();

			if (data == null || data.length() < 1)
				break;

			Cursor cursor = null;

			Uri allMessage = Uri.parse("content://sms/");
			cursor = mContext.getContentResolver().query(allMessage, null, "address in ( ? , ?) ",
					new String[] { data, data.replace("-", "") }, null);

			ArrayList<Integer> smsThreadId = new ArrayList<Integer>();
			if (cursor != null && cursor.getCount() > 0) {
				cursor.moveToFirst();
				while (cursor.isAfterLast() == false) {
					MessageInfo info = new MessageInfo();

					info.setId(cursor.getInt(cursor.getColumnIndex(Sms._ID)));
					info.setBody(cursor.getString(cursor.getColumnIndex("body")));
					info.setDate(cursor.getLong(cursor.getColumnIndex("date")));
					info.setNumber(cursor.getString(cursor.getColumnIndex("address")));
					info.setRead(cursor.getInt(cursor.getColumnIndex("read")));
					info.setType(cursor.getInt(cursor.getColumnIndex("type")));
					
					int thread_Id = cursor.getInt(cursor.getColumnIndex("thread_id"));
							
					smsThreadId.add(thread_Id);
					conversion.addMessageInfo(info);
					isReturn = true;

					cursor.moveToNext();

					//Log.d("CH_DEBUG", "############ SMS __ ID :" + info.getId() + ":::"  + thread_Id );
					// 삭제.
					//mContext.getContentResolver().delete(allMessage, "_id = " + info.getId(), null);
				}
			}

			if (cursor != null)
				cursor.close();
			
			
			allMessage =  Uri.parse("content://mms/");
			
			cursor = mContext.getContentResolver().query(allMessage, null, null, null, null);

			if (cursor != null && cursor.getCount() > 0) {
				cursor.moveToFirst();

				int index_id = cursor.getColumnIndex("_id");
				int index_date = cursor.getColumnIndex("date");
				int index_ct_t = cursor.getColumnIndex("ct_t");
				int index_m_type = cursor.getColumnIndex("m_type");
				int index_threadid = cursor.getColumnIndex("thread_id");
				int index_mId = cursor.getColumnIndex("m_id");

				while (cursor.isAfterLast() == false) {

					final String Id = cursor.getString(index_id);
					final String ThreadId = cursor.getString(index_threadid);
					
					
					final String returnNumber = getAddressNumber(Integer.parseInt(Id));
					
					
					/*  해당 번호 체크 하는 부분		
						if (!(data.equals(returnNumber) || data.replace("-", "").equals(returnNumber))) {
							cursor.moveToNext();
							continue;
						}
					*/

					/*
					if ( returnNumber == null ) {
						cursor.moveToNext();
						Log.e("CH_DEBUG", "######### 삭제 메시지");
						
						//final Uri thread = Uri.parse("content://mms/inbox/" + Id);
						//mContext.getContentResolver().delete(thread, null, null);
						
						continue;
					}
					*/
					
					/**  MMS 로그 찍기.*/
					StringBuilder build = new StringBuilder();	
					build.append(" ##### NUMBER    : " + returnNumber + " :: " );
					for (int i = 0; i < cursor.getColumnCount(); i++) {

						String columnName = cursor.getColumnName(i);
						String columnValue = cursor.getString(cursor.getColumnIndex(columnName));
						build.append("#####  NAME  :  " + columnName + " -- VALUE "+  columnValue +"\n");
					}
					
					
					Log.d("CH_DEBUG", "########### build : " +build.toString());
					/**/
					MessageInfo messageInfo = new MessageInfo();

					long cDate = cursor.getLong(index_date) * 1000;

					// 128 보낸 132 받은.
					String cType = cursor.getString(index_m_type);
					String cT = cursor.getString(index_ct_t);

					messageInfo.setNumber(returnNumber);
					messageInfo.setDate(cDate);
					// * 1 : 수신 2: 발신
					messageInfo.setType(cType.equals("128") ? 2 : 1);

					// MMS 데이터 획득..처리.
					final Uri mmsPartUri = Uri.parse("content://mms/part/");
					final String selectOb = "mid = ?";
					final Cursor partCursor = mContext.getContentResolver(). query(mmsPartUri, null, selectOb,
							new String[] { Id }, null);
					MESSAGE_TYPE tempType = MESSAGE_TYPE.SMS;

					if (partCursor != null && partCursor.getCount() > 0) {
						partCursor.moveToFirst();

						// text/plain , image/jpeg 만 골라 내라.
						final int index_part_ct = partCursor.getColumnIndex("ct");
						final int index_part_text = partCursor.getColumnIndex("text");
						final int index_part_data = partCursor.getColumnIndex("_data");

						
						while (partCursor.isAfterLast() == false) {
							

							String[] coloumns = partCursor.getColumnNames();
							String[] values = null;

							if (values == null)
								values = new String[coloumns.length];

							for (int i = 0; i < partCursor.getColumnCount(); i++) {
								values[i] = partCursor.getString(i);
							}
							/*
							for (int indexxss = 0; indexxss < values.length; indexxss++) {
								Log.e("CH_DEBUG", "### DATA : " + indexxss + "::" + values[indexxss]);
							}
							 */
							//GetMmsAttachment(values[0],values[12],values[4]);
							
							final String part_ct = partCursor.getString(index_part_ct);

							if (part_ct == null) {
								partCursor.moveToNext();
								continue;
							}

							if (part_ct.equalsIgnoreCase("text/plain")) {
								final String part_text = partCursor.getString(index_part_text);
								messageInfo.setBody(part_text);
								if (tempType.equals(MESSAGE_TYPE.SMS) || tempType.equals(MESSAGE_TYPE.MMS_TEXT))
									tempType = MESSAGE_TYPE.MMS_TEXT;
								else
									tempType = MESSAGE_TYPE.MMS_MIX;
							} else if (part_ct.equalsIgnoreCase("image/jpeg")) {
								byte[] bytesss= GetMmsAttachment(values[0],values[12],values[4]);
								messageInfo.addBitMapByte(bytesss);
								
								if (tempType.equals(MESSAGE_TYPE.SMS) || tempType.equals(MESSAGE_TYPE.MMS_IMAGE))
									tempType = MESSAGE_TYPE.MMS_IMAGE;
								else
									tempType = MESSAGE_TYPE.MMS_MIX;

							}

							partCursor.moveToNext();

						}
					}

					messageInfo.setMessagType(tempType);
					isReturn = true;

					
					conversion.addMessageInfo(messageInfo);
					// arrayInfo.add(messageInfo);

					if (partCursor != null)
						partCursor.close();

					cursor.moveToNext();
					
					// MMS 삭제 
					
					final Uri thread = Uri.parse("content://mms/inbox/" + Id);
					mContext.getContentResolver().delete(thread, null, null);
					

					/*
					mContext.getContentResolver().delete(allMessage, "_id = " + Id, null);
					
					final Uri thread = Uri.parse("content://mms/inbox/" + Id);
					mContext.getContentResolver().delete(c, "_id = " + Id, null);
					mContext.getContentResolver().delete(thread, null, null);
					*/
				}

			}

			if (cursor != null)
				cursor.close();
			
			// SMS 와 MMS 삭제 ..
			// SMS 삭제 시도 __ Thread_ID 별
				for  ( Integer thread_ids : smsThreadId ) { 
				final Uri thread = Uri.parse("content://sms/conversations/"+ thread_ids);
				mContext.getContentResolver().delete(thread, null, null);
			}
			
			

			// //////////////////////// 전화 목록 체크 ///////////////////////////////
			Cursor callCursor = null;

			/*
			 * if (mType == CallLog.Calls.OUTGOING_TYPE || mType == CallLog.Calls.INCOMING_TYPE || mType ==
			 * CallLog.Calls.MISSED_TYPE) { cursor = getContentResolver().query(CallLog.Calls.CONTENT_URI, null,
			 * CallLog.Calls.TYPE + "= ?", new String[] { String.valueOf(CallLog.Calls.OUTGOING_TYPE) },
			 * CallLog.Calls.DEFAULT_SORT_ORDER); } else {
			 */

			final String selectOb = "number in ( ? , ?) ";
			
			callCursor = mContext.getContentResolver().query(CallLog.Calls.CONTENT_URI, null, selectOb,
					new String[] { data, data.replace("-", "") }, CallLog.Calls.DEFAULT_SORT_ORDER);

			if (callCursor != null && callCursor.getCount() > 0) {
				callCursor.moveToFirst();

				while (callCursor.isAfterLast() == false) {

					CallInfo info = new CallInfo();

					int callId = callCursor.getInt(callCursor.getColumnIndex(CallLog.Calls._ID));
					info.setType(callCursor.getInt(callCursor.getColumnIndex(CallLog.Calls.TYPE)));
					info.setName(callCursor.getString(callCursor.getColumnIndex(CallLog.Calls.CACHED_NAME)));
					info.setNumber(callCursor.getString(callCursor.getColumnIndex(CallLog.Calls.NUMBER)));
					info.setDuration(callCursor.getLong(callCursor.getColumnIndex(CallLog.Calls.DURATION)));
					info.setTime(callCursor.getLong(callCursor.getColumnIndex(CallLog.Calls.DATE)));

					conversion.addCallInfo(info);

					Log.e("CH_DEBUG", "############# CALL : " + info.getName() + "::: " + info.getNumber());
					// 삭제.
					//mContext.getContentResolver().delete(CallLog.Calls.CONTENT_URI, CallLog.Calls._ID + "= " + callId, null);

					// arrayInfo.add(info);
					isReturn = true;
					callCursor.moveToNext();

				}
			}

			if (callCursor != null)
				callCursor.close();

		}		

		return isReturn;
	}

	/**
	 * MMS 수발신 번호체크
	 * 
	 * @param id
	 * @return
	 */
	private String getAddressNumber(int id) {
		 String selectionAdd = new String("msg_id=" + id);
		String uriStr = MessageFormat.format("content://mms/{0}/addr", id);
		Uri uriAddress = Uri.parse(uriStr);
		Cursor cAdd = mContext.getContentResolver().query(uriAddress, null, selectionAdd, null, null);
		String name = null;
		if (cAdd != null && cAdd.moveToFirst()) {
			do {
				Log.e("CH_DEBUG", "### getAddressNumber  : GOGO");;
				String number = cAdd.getString(cAdd.getColumnIndex("address"));
				if (number != null) {
					try {
						Long.parseLong(number.replace("-", ""));
						name = number;
					} catch (NumberFormatException nfe) {
						Log.e("CH_DEBUG", "### getAddressNumber ERRO  : " + nfe.toString());;
						if (name == null) {
							name = number;
						}
					}
				}

				String[] coloumns = cAdd.getColumnNames();
				String[] values = null;

				if (values == null)
					values = new String[coloumns.length];

				for (int i = 0; i < cAdd.getColumnCount(); i++) {
					values[i] = cAdd.getString(i);
				}

				for (int indexxss = 0; indexxss < values.length; indexxss++) {
					Log.e("CH_DEBUG", "### getAddressNumber  : " + coloumns[indexxss] + "::" + values[indexxss]);
				}
				
				
			} while (cAdd.moveToNext());
		}
		if (cAdd != null) {
			cAdd.close();
		}

		if (name == null) {
			// ContentValues valyes = new ContentValues();
			// valyes.put(key, value)
			// getContentResolver().insert(uriAddress, null, null, null, null);
		}
		return name;
	}

}
